<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>集合管理</title>
    <!-- Element UI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 自定义CSS -->
    <link rel="stylesheet" href="../css/style.css">
    <!-- Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- Element UI JS -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- API请求管理 -->
    <script src="../js/api.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",Arial,sans-serif;
        }
        .component-container {
            padding: 15px;
        }
        .component-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .active-row {
            background-color: #f0f9eb !important;
        }
        .collection-status {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .active {
            background-color: #67C23A;
        }
        .inactive {
            background-color: #909399;
        }
    </style>
    <script>
        // 使用父窗口的全局变量
        const API_BASE_URL = window.parent.appGlobal.API_BASE_URL || '/api';
    </script>
</head>
<body>
    <div id="app">
        <div class="component-container">
            <div class="component-header">
                <h3>集合管理</h3>
                <el-button type="primary" size="small" @click="dialogVisible = true">新建集合</el-button>
            </div>
            
            <el-table
                :data="collections"
                v-loading="loading"
                :row-class-name="getRowClass"
                style="width: 100%">
                <el-table-column label="集合名称" width="180">
                    <template slot-scope="scope">
                        <div>
                            <span class="collection-status" :class="scope.row.is_active ? 'active' : 'inactive'"></span>
                            {{ scope.row.name }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="文档数量" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.document_count }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="100">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.is_active ? 'success' : 'info'" size="mini">
                            {{ scope.row.is_active ? '活动' : '非活动' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            @click="useCollection(scope.row)">
                            使用</el-button>
                        <el-button
                            size="mini"
                            type="danger"
                            @click="deleteCollection(scope.row)">
                            删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
            <!-- 新建集合对话框 -->
            <el-dialog title="新建集合" :visible.sync="dialogVisible" width="30%" @closed="resetForm">
                <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                    <el-form-item label="集合名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入集合名称"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="createCollection" :loading="loading">确 定</el-button>
                </span>
            </el-dialog>
        </div>
    </div>

    <script>
        // 页面脚本
        new Vue({
            el: '#app',
            data() {
                return {
                    collections: [],
                    loading: false,
                    dialogVisible: false,
                    form: {
                        name: ''
                    },
                    rules: {
                        name: [
                            { required: true, message: '请输入集合名称', trigger: 'blur' },
                            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                        ]
                    }
                };
            },
            computed: {
                // 从全局变量获取活动集合
                activeCollection() {
                    return window.parent.appGlobal.activeCollection;
                }
            },
            created() {
                this.fetchCollections();
            },
            methods: {
                // 获取所有集合
                fetchCollections() {
                    this.loading = true;
                    axios.get(`${API_BASE_URL}/collections`)
                        .then(response => {
                            console.log('获取到的集合数据:', response.data);
                            this.collections = response.data.collections || [];
                            
                            // 检查是否需要自动使用上次选择的集合
                            this.checkAutoSelectCollection();
                        })
                        .catch(error => {
                            console.error('获取集合列表失败:', error);
                            this.$message.error('获取集合列表失败');
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                },
                
                // 检查是否需要自动选择保存的集合
                checkAutoSelectCollection() {
                    // 如果已有活动集合，无需处理
                    if (this.activeCollection) return;
                    
                    // 尝试从localStorage读取保存的集合
                    const storedCollection = localStorage.getItem('activeCollection');
                    if (!storedCollection) return;
                    
                    try {
                        const collection = JSON.parse(storedCollection);
                        // 在集合列表中查找这个集合
                        const foundCollection = this.collections.find(c => c.name === collection.name);
                        if (foundCollection) {
                            // 找到集合，自动选择它
                            this.useCollection(foundCollection, true);
                        }
                    } catch (e) {
                        console.error('解析保存的集合数据失败:', e);
                    }
                },
                
                // 创建新集合
                createCollection() {
                    this.$refs.form.validate((valid) => {
                        if (valid) {
                            this.loading = true;
                            // 修改请求体格式，符合后端API期望的结构
                            const data = { 
                                collection: {
                                    name: this.form.name
                                }
                            };
                            
                            axios.post(`${API_BASE_URL}/collections`, data)
                                .then(() => {
                                    this.$message({
                                        message: `成功创建集合: ${this.form.name}`,
                                        type: 'success'
                                    });
                                    this.dialogVisible = false;
                                    this.form.name = '';
                                    this.fetchCollections();
                                })
                                .catch(error => {
                                    console.error('创建集合失败:', error);
                                    this.$message.error('创建集合失败: ' + (error.response?.data?.error || error.message));
                                })
                                .finally(() => {
                                    this.loading = false;
                                });
                        }
                    });
                },
                
                // 使用集合
                useCollection(collection, silent = false) {
                    this.loading = true;
                    axios.post(`${API_BASE_URL}/collections/${collection.name}/use`)
                        .then(() => {
                            // 构建活动集合对象，确保它具有UI需要的字段
                            const activeCollection = {
                                name: collection.name,
                                document_count: collection.document_count,
                                is_active: true
                            };
                            
                            // 保存到localStorage
                            localStorage.setItem('activeCollection', JSON.stringify(activeCollection));
                            
                            // 直接使用全局变量
                            window.parent.appGlobal.activeCollection = activeCollection;
                            
                            // 通知父页面应用更新
                            if (window.parent.app && window.parent.app.setActiveCollection) {
                                window.parent.app.setActiveCollection(activeCollection);
                            } else {
                                // 如果无法通过父页面更新，直接显示消息
                                if (!silent) {
                                    this.$message({
                                        message: `已切换到集合: ${collection.name}`,
                                        type: 'success'
                                    });
                                }
                            }
                            
                            this.fetchCollections();
                        })
                        .catch(error => {
                            console.error('切换集合失败:', error);
                            this.$message.error('切换集合失败: ' + (error.response?.data?.error || error.message));
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                },
                
                // 删除集合
                deleteCollection(collection) {
                    this.$confirm(`此操作将永久删除集合 "${collection.name}"，是否继续?`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.loading = true;
                        axios.delete(`${API_BASE_URL}/collections/${collection.name}`)
                            .then(() => {
                                this.$message({
                                    message: `成功删除集合: ${collection.name}`,
                                    type: 'success'
                                });
                                
                                // 如果删除的是当前活动集合，清空activeCollection
                                if (this.activeCollection && this.activeCollection.name === collection.name) {
                                    // 从localStorage中删除
                                    localStorage.removeItem('activeCollection');
                                    
                                    // 直接使用全局变量
                                    window.parent.appGlobal.activeCollection = null;
                                    
                                    // 通知父页面应用更新
                                    if (window.parent.app && window.parent.app.setActiveCollection) {
                                        window.parent.app.setActiveCollection(null);
                                    }
                                }
                                
                                this.fetchCollections();
                            })
                            .catch(error => {
                                console.error('删除集合失败:', error);
                                this.$message.error('删除集合失败: ' + (error.response?.data?.error || error.message));
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }).catch(() => {
                        // 取消删除操作
                    });
                },
                
                // 清空表单
                resetForm() {
                    this.$refs.form.resetFields();
                },
                
                // 计算集合行的类名
                getRowClass({row}) {
                    return this.activeCollection && row.name === this.activeCollection.name ? 'active-row' : '';
                }
            }
        });
    </script>
</body>
</html>